<?php
class WomenModel extends DbModel {
	protected $data = array();
	
	public $count = '';
	
	//正则验证条件.
	protected $regex = array(
		'nickname' => '/^[A-Za-z0-9_\-\x{4e00}-\x{9fa5}]{2,15}$/u',
		'age' => '/^\d{2,2}$/',
		'qq' => '/^\d{5,12}$/',
		'mobile' => '/^\d{11,11}$/'
	);
	
	public function initData($data) {
		$this->data['nickname'] = preg_match($this->regex['nickname'], $data['nickname']) ? $data['nickname'] : '';
		$this->data['age'] = preg_match($this->regex['age'], $data['age']) ? $data['age'] : '';
		$this->data['hometown'] = $data['jiguan_guojia'].','.$data['jiguan_sheng'].','.$data['jiguan_shi'];
		$this->data['location'] = $data['suozaidi_city'];
		$this->data['stature'] = implode(',', $data['tag']);
		$this->data['beautiful'] = $data['fuwu'];
		$this->data['qq'] = preg_match($this->regex['qq'], $data['qq']) ? $data['qq'] : '';
		$this->data['mobile'] = preg_match($this->regex['mobile'], $data['shouji']) ? $data['shouji'] : '';
// 		$this->data['images'] = $data['nickname'];
// 		$this->data['thumb_images'] = $data['nickname'];
		$this->data['brief'] = $data['jianjie'];
		$this->data['shengao'] = $data['shengao'];
		$this->data['tizhong'] = $data['tizhong'];
		$this->data['xiong'] = $data['xiongwei'];
		$this->data['createtime'] = time();
		$this->data['ipaddress'] = $this->getIpAdress();
		$this->data['iparea'] = '';
		$this->data['disabled'] = 0;
		$this->data['password'] = md5(time().mt_rand(1, 9));
		$this->data['updatetime'] = time();
		$this->data['attest'] = 0;
		
		if ($this->data['nickname'] == '') {
			return false;
		}
		
		if ($this->data['age'] == '') {
			return false;
		}
		
		if ($this->data['qq'] == '') {
			return false;
		}
		
		if ($this->data['mobile'] == '') {
			return false;
		}
		
		foreach ($this->data as $d_key => $d_val) { $this->data[$d_key] = mysql_real_escape_string($d_val);}
		
		return true;;
	}
	
	public function img2thumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
	{
		if(!is_file($src_img))
		{
			return false;
		}
		$ot = $this->fileext($dst_img);
		$otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
		$srcinfo = getimagesize($src_img);
		$src_w = $srcinfo[0];
		$src_h = $srcinfo[1];
		$type  = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
		$createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);
	
		$dst_h = $height;
		$dst_w = $width;
		$x = $y = 0;
	
		/**
		 * 缩略图不超过源图尺寸（前提是宽或高只有一个）
		 */
		if(($width> $src_w && $height> $src_h) || ($height> $src_h && $width == 0) || ($width> $src_w && $height == 0))
		{
			$proportion = 1;
		}
		if($width> $src_w)
		{
			$dst_w = $width = $src_w;
		}
		if($height> $src_h)
		{
			$dst_h = $height = $src_h;
		}
	
		if(!$width && !$height && !$proportion)
		{
			return false;
		}
		if(!$proportion)
		{
			if($cut == 0)
			{
				if($dst_w && $dst_h)
				{
					if($dst_w/$src_w> $dst_h/$src_h)
					{
						$dst_w = $src_w * ($dst_h / $src_h);
						$x = 0 - ($dst_w - $width) / 2;
					}
					else
					{
						$dst_h = $src_h * ($dst_w / $src_w);
						$y = 0 - ($dst_h - $height) / 2;
					}
				}
				else if($dst_w xor $dst_h)
				{
					if($dst_w && !$dst_h)  //有宽无高
					{
						$propor = $dst_w / $src_w;
						$height = $dst_h  = $src_h * $propor;
					}
					else if(!$dst_w && $dst_h)  //有高无宽
					{
						$propor = $dst_h / $src_h;
						$width  = $dst_w = $src_w * $propor;
					}
				}
			}
			else
			{
				if(!$dst_h)  //裁剪时无高
				{
					$height = $dst_h = $dst_w;
				}
				if(!$dst_w)  //裁剪时无宽
				{
					$width = $dst_w = $dst_h;
				}
				$propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
				$dst_w = (int)round($src_w * $propor);
				$dst_h = (int)round($src_h * $propor);
				$x = ($width - $dst_w) / 2;
				$y = ($height - $dst_h) / 2;
			}
		}
		else
		{
			$proportion = min($proportion, 1);
			$height = $dst_h = $src_h * $proportion;
			$width  = $dst_w = $src_w * $proportion;
		}
	
		$src = $createfun($src_img);
		$dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
		$white = imagecolorallocate($dst, 255, 255, 255);
		imagefill($dst, 0, 0, $white);
	
		if(function_exists('imagecopyresampled'))
		{
			imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
		}
		else
		{
			imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
		}
		$otfunc($dst, $dst_img);
		imagedestroy($dst);
		imagedestroy($src);
		return true;
	}
	
	public function fileext($file)
	{
		return pathinfo($file, PATHINFO_EXTENSION);
	}
	
	public function addData() {
		if ($this->initData($_POST) == FALSE) {
			return false;
		}
		
		$sql = "INSERT INTO ".$this->db_prefix."women (`".implode('`,`', array_keys($this->data))."`)";
		$sql .= " VALUES ('".implode("','", array_values($this->data))."')";
		if ($this->db->exec($sql)) {
			$women_id = $this->db->lastInsertId();
			$this->uploadFiles($this->db->lastInsertId());
			$this->db->exec('UPDATE '.$this->db_prefix.'women SET images="'.implode(',', $this->data['images']).'" WHERE women_id='.$women_id);
			return true;
		}
		
		return false;
	}
	
	public function uploadFiles($women_id) {
		if (isset($_FILES['women']['name']) && count($_FILES['women']['name'])) {
			$upload_dir = APP_UPLOAD_DIR . DIRECTORY_SEPARATOR .'women';
			if (file_exists($upload_dir) == FALSE) mkdir($upload_dir, 0777);
			$upload_dir = $upload_dir . DIRECTORY_SEPARATOR . $women_id;
			if (file_exists($upload_dir) == FALSE) mkdir($upload_dir, 0777);
			$rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i";

			foreach ($_FILES['women']['name'] as $key => $name) {
				$imagesize = round($_FILES['women']['size'][$key] / (1024 * 1024));
				$safe_filename = preg_replace( array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($name));
				//大于5M的图片不允许上传.
				if ($imagesize > 5) {
					continue;
				}
					
				if (preg_match($rEFileTypes, strrchr($safe_filename, '.')) == FALSE) {
					continue;
				}
				
				$file_name = md5($name).'.'.strtolower(end(explode('.', $name)));
				$new_file = $upload_dir.DIRECTORY_SEPARATOR.$file_name;
				move_uploaded_file($_FILES['women']['tmp_name'][$key], $new_file);
				$this->data['images'][] = $file_name;
				$this->img2thumb($new_file, $new_file, 800, 600);
			}
		}		
	}
	
	public function getData() {
		return $this->data;
	}
	
	public function getIpAdress() {
	    if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
	        $onlineip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	    } elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
	        $onlineip = $_SERVER['HTTP_CLIENT_IP'];
	    } else{
	        $onlineip = $_SERVER['REMOTE_ADDR'];
	    }
	     
	    return $onlineip;
	}
	
	/**
	 * 取得列表,默认列出15条数据.
	 * @param string $condation 默认检索条件.
	 * @return array 
	 */
	public function getList($condation = "`disabled` = '0' ORDER BY `createtime` DESC", $page = 1, $limit = 18) {
		$sql = "SELECT * FROM `".$this->db_prefix."women` WHERE ".$condation.' LIMIT '.($page-1)*$limit.','.$limit;
		$queryCount = "SELECT COUNT(*) AS count FROM `".$this->db_prefix."women` WHERE ".$condation;
		
		$data = $this->db->findOne($queryCount);
		$this->count = $data['count'];
		return $this->db->findAll($sql);
	}
	
	/**
	 * @param  $totalCount  数据总数.
	 * @param  $page        当前页面
	 * @param  $pagesize    每页显示数据
	 * @param  $offset      位移
	 */
	public function page($totalCount, $page, $pagesize, $offset = 4) {
		$start_offset = 1;
		$end_offset = 1;
		$arr = array();
		 
		//总页数
		$pageCount = ceil($totalCount / $pagesize);
		$page_left_offset = ($page - $offset);
		$page_right_offset = ($page + $offset);
	
		//计算出中间页
		if ($page_left_offset <= 1) {
			$page_middle_number = ($offset + 1);
		}
		 
		if ($page_right_offset >= $pageCount) {
			$page_middle_number = ($pageCount - $offset);
		}
		 
		if ($page_left_offset > 1 && $page_right_offset < $pageCount) {
			$page_middle_number = $page;
		}
		 
		//计算开始和结束.
		$start_offset = ($page_middle_number - $offset);
		$end_offset = ($page_middle_number + $offset);
		 
		if ($start_offset <= 1) {
			$start_offset = 1;
		}
		 
		if ($end_offset >= $pageCount) {
			$end_offset = $pageCount;
		}
		 
	
		for ($i = $start_offset; $i <= $end_offset; $i++) {
			$arr[] = $i;
		}
		 
		return $arr;
	}
	
	/**
	 * 根据ID获取 
	 */
	public function getWomenById($women_id) {
		$sql = "SELECT * FROM `".$this->db_prefix."women` WHERE women_id={$women_id}";
		return $this->db->findOne($sql);
	}
}